/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.github.apk.arsc;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.LinkedList;
import java.util.List;

import com.google.common.base.Preconditions;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

/**
 * Represents an XML chunk structure.
 *
 * <p>An XML chunk can contain many nodes as well as a string pool which contains all of the strings
 * referenced by the nodes.
 */
public final class XmlChunk extends ChunkWithChunks {
  public static final String XML_NAME = "AndroidManifest.xml";
  private transient StringPoolChunk stringPoolChunk;

  protected XmlChunk(ByteBuffer buffer, @Nullable Chunk parent) {
    super(buffer, parent);
  }

  public static XmlChunk parse(byte[] resourceBytes) throws IOException {
    if (resourceBytes == null) {
      throw new IOException(String.format("Unable to find %s in APK.", XML_NAME));
    }
    List<Chunk> chunks = new ResourceFile(resourceBytes).getChunks();
    Preconditions.checkState(chunks.size() == 1,
            "%s should only have one root chunk.", XML_NAME);
    Chunk resourceTable = chunks.get(0);
    Preconditions.checkState(resourceTable instanceof XmlChunk,
            "%s root chunk must be a XmlChunk.", XML_NAME);
    return (XmlChunk) resourceTable;
  }


  @Override
  protected Type getType() {
    return Chunk.Type.XML;
  }

  /** Returns a string at the provided (0-based) index if the index exists in the string pool. */
  public String getString(int index) {
    StringPoolChunk stringPoolChunk= getStringPoolChunk();
    if(stringPoolChunk != null){
      return stringPoolChunk.getString(index);
    }
    throw new IllegalStateException("XmlChunk did not contain a string pool.");
  }

  public int addString(String value) {
    StringPoolChunk stringPoolChunk= getStringPoolChunk();
    if(stringPoolChunk != null){
      return stringPoolChunk.addString(value);
    }
    throw new IllegalStateException("XmlChunk did not contain a string pool.");
  }

  public StringPoolChunk getStringPoolChunk(){
    if(stringPoolChunk != null){
      return stringPoolChunk;
    }
    for (Chunk chunk : getChunks().values()) {
      if (chunk instanceof StringPoolChunk) {
        stringPoolChunk = ((StringPoolChunk) chunk);
        return stringPoolChunk;
      }
    }
    throw new IllegalStateException("XmlChunk did not contain a string pool.");
  }

  @Nullable
  public XmlStartElementChunk getFirstStartTag(@NotNull String name){
    for(Chunk chunk : chunks.values()){
      if(chunk instanceof XmlStartElementChunk){
        XmlStartElementChunk startElementChunk = (XmlStartElementChunk)chunk;
        if(name.equals(startElementChunk.getFullName())){
          return startElementChunk;
        }
      }
    }
    return null;
  }

  public List<XmlStartElementChunk> getStartTags(String name){
    List<XmlStartElementChunk> list = new LinkedList<>();
    for(Chunk chunk : chunks.values()){
      if(chunk instanceof XmlStartElementChunk){
        XmlStartElementChunk startElementChunk = (XmlStartElementChunk)chunk;
        if(name.equals(startElementChunk.getFullName())){
          list.add(startElementChunk);
        }
      }
    }
    return list;
  }
}
